package com.harmonyos.zxing;

import com.google.zxing.journeyapps.barcodescanner.BusHelper;
import com.google.zxing.journeyapps.barcodescanner.CaptureManager;
import com.google.zxing.journeyapps.barcodescanner.DecoratedBarcodeView;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.window.service.Window;
import ohos.agp.window.service.WindowManager;
import ohos.utils.PacMap;

public class ToolbarCaptureAbility extends Ability implements BusHelper.Observable {
    private CaptureManager capture;
    private DecoratedBarcodeView barcodeScannerView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_toolbar_capture);
        WindowManager windowManager = WindowManager.getInstance();
        Window window = windowManager.getTopWindow().get();
        window.setTransparent(true);

        Component back = findComponentById(ResourceTable.Id_back);
        barcodeScannerView = (DecoratedBarcodeView) findComponentById(ResourceTable.Id_zxing_barcode_scanner);
        capture = new CaptureManager(this, barcodeScannerView);
        capture.initializeFromIntent(this.getIntent(), null);

        back.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                onBackPressed();
                capture.onPause();
                capture.onDestroy();
            }
        });

        BusHelper.getINSTANCE().register("CameraPreviewStarted", this);
    }

    @Override
    protected void onActive() {
        super.onActive();
        capture.onResume();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        capture.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        BusHelper.getINSTANCE().unRegister(this);
        capture.onDestroy();
    }

    @Override
    public void onRestoreAbilityState(PacMap inState) {
        super.onRestoreAbilityState(inState);
        capture = new CaptureManager(this, barcodeScannerView);
        capture.initializeFromIntent(this.getIntent(), inState);
    }

    @Override
    public void onSaveAbilityState(PacMap outState) {
        super.onSaveAbilityState(outState);
        capture.onSaveInstanceState(outState);
    }

    @Override
    public void onSubscribe(Object object) {
        if (capture != null)
            capture.decode();
    }
}
